package com.trc202.MemoryManagers;
//Term Project Ted Chandler and Daniel Moore
import java.util.ArrayList;
	
import com.trc202.CS350.Job;
import com.trc202.CS350.MemorySegment;

public class MemoryManager {

	Job[] jobs = null;
	MemorySegment[] memory = null;
	public MemoryManager(Job[] jobs, MemorySegment[] memory){
		this.jobs = jobs;
		this.memory = memory;
	}
	
	/**
	 * Method which is to be overridden by classes which implement certain types of ordering for RAM
	 */
	public void manageMemory(){
		freeCompletedJobs();
	}
	
	/**
	 * Returns a list of available jobs which are currently waiting for a position in RAM
	 * @return ArrayList of available Jobs
	 */
	protected ArrayList<Job> getAvalableJobs(){
		ArrayList<Job> avalable = new ArrayList<Job>();
		for(int x = 0; x < jobs.length; x++){
			if(jobs[x].getStatus() == Job.Status.WAITING){
				avalable.add(jobs[x]);
			}
		}
		return avalable;
	}
	
	/**
	 * Removes Completed Jobs from memory
	 */
	protected void freeCompletedJobs(){
		for(Job j : jobs){
			if(j.isFinished() && j.getAssignedSegmentNum() >= 0){
				memory[j.getAssignedSegmentNum()].setMBUsed(0);
				j.setAssignedSegmentNum(-1);
				j.setStatus(Job.Status.FINISHED);
			}
		}
	}
	
	/**
	 * Returns a ArrayList of Memory Segments which are currently not in use
	 * @return ArrayList of MemorySegments which are not in use
	 */
	protected ArrayList<MemorySegment> getFreeRam(){
		ArrayList<MemorySegment> freeSpaces = new ArrayList<MemorySegment>();
		for(int x = 0; x < memory.length; x++){
			if(!memory[x].isInUse()){
				freeSpaces.add(memory[x]);
			}
		}
		return freeSpaces;
	}
	
	/**
	 * @return Total ram currently wasted
	 */
	public int getTotalWastedMemory(){
		int memoryWasted = 0;
		for(MemorySegment m : memory){
			memoryWasted = memoryWasted + m.getWasted();
		}
		return memoryWasted;
	}

}
